<?php

namespace app\admin\controller;

use app\common\controller\Adminbase;
use app\common\model\CateModel;
use app\common\model\SourceModel;

/**
 *
 */
class Source extends Adminbase
{

    /**
     * TeamSourceModel模型对象
     * @var \app\admin\model\TeamSourceModel
     */
    protected $modelClass = null;

    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = new SourceModel();

    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            if ($this->admin['roleid'] != 1) {
                $map[] = ['yzn_apply_team.aid', '=', $this->admin['id']];
            }
            [$page, $limit, $where, $sort, $order] = $this->buildTableParames();
            $list = $this->modelClass
                ->withJoin(['cate'])
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);


            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['cate_name']);
            }
            $result = ["code" => 0, "count" => $list->total(), "data" => $list->items()];

            return json($result);
        }
        return $this->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            try {
                $params = $this->request->post();
                $aid = $this->admin['id'];
                if($this->admin['roleid'] == 1){
                    $aid = 0;
                }
                if ($params['kind'] == 4) {
                    $data = [];
                    foreach ($params['video'] as $value) {
                        $filename = basename($value);
                        $filenameWithoutExt = pathinfo($filename, PATHINFO_FILENAME);
                         $file = explode('-',$filenameWithoutExt);
                        if(!isset($file[1])){
                            $this->error('请填写话题');
                        }
                        $tags = str_replace('，', ',', $file[1]);
                        
                        $data[] = [
                            'cid' => $params['cid'],
                            'title' => $file[0],
                            'annex' => $value,
                            'kind' => 4,
                            'hashtag' => $tags,
                            'aid' => $aid,
                        ];
                    }
                    $this->modelClass->saveAll($data);
                } else {
                    $data = [
                        'cid' => $params['cid'],
                        'title' => $params['title'],
                        'annex' => $params['pic'],
                        'kind' => 2,
                        'hashtag' => $params['hashtag'],
                        'aid' => $this->admin['id'],
                    ];
                    $this->modelClass->save($data);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success("添加成功！", url('index'));
        }
        $area = CateModel::where(['status' => 1])->field('id,cate_name')->select()->toArray();
        $this->assign('cate', $area);
        return $this->fetch();
    }


    public function edit()
    {
        $id  = $this->request->param('id/d', 0);
        $row = $this->modelClass->get($id);
        if($row['kind'] == 2){
            $row['pic'] =  $row['annex'];
            $row['video'] = '';
        }else{
            $row['video'] =  $row['annex'];
            $row['pic'] = '';
        }
        if (!$row) {
            $this->error('记录未找到');
        }
        if ($this->request->isPost()) {
            $this->token();
            $params             = $this->request->post('row');
            if($params['kind'] == 4 && $params['video']){
                $params['annex'] = $params['video'];
            }elseif ($params['kind'] == 2 && $params['pic']){
                $params['annex'] = $params['pic'];
            }else{
                $this->error('请上传内容');
            }

            try {
                $row->allowField(true)->save($params);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success("修改成功！");
        }
        $area = CateModel::where(['status' => 1])->field('id,cate_name')->select()->toArray();
        $this->assign('cate',$area);
        $this->assign("data", $row);
        return $this->fetch();
    }


}
